package cn.hznc.utils;

import cn.hznc.excel.BaseReadListener;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.MapUtils;
import com.alibaba.fastjson.JSON;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

public class EasyExcelUtil {

    /**
     * 按模板导入
     *
     * @param response response
     * @param fileName fileName
     * @throws IOException
     */
    public static void downloadExcel(HttpServletResponse response,String fileName) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            response.flushBuffer();
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = MapUtils.newHashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    /**
     * 读取excel 文件
     *
     * @param file     文件
     * @param cl       类对象
     * @param listener 参数校验监听器
     */
    public static <T> Map<Integer,String> importExcel(MultipartFile file, Class<T> cl, BaseReadListener<T> listener) {
        try {
            EasyExcel.read(file.getInputStream(), cl, listener).sheet().doRead();
            return listener.getErrorMessageMap();
        } catch (IOException e) {
            return null;
        }
    }

}
